<?php
class Forgot_Password_API_Endpoint{
	
	
	public function __construct(){
		add_filter('query_vars', array($this, 'add_query_vars'), 0);
		add_action('parse_request', array($this, 'sniff_requests'), 0);
		add_action('init', array($this, 'add_endpoint'), 0);
	}	
	
	/** Add public query vars
	*	@param array $vars List of current public query vars
	*	@return array $vars 
	*/
	public function add_query_vars($vars){
		$vars[] = '__api';
		$vars[] = 'user';
		$vars[] = 'action';
		return $vars;
	}
	
	/** Add API Endpoint
	*	This is where the magic happens - brush up on your regex skillz
	*	@return void
	*/
	public function add_endpoint(){
		add_rewrite_rule('^api/forgot_password/([0-9a-zA-Z]+)?/?','index.php?__api=1&action=fe_forgot_password&user=$matches[1]','top');
	}
 
	/**	Sniff Requests
	*	This is where we hijack all API requests
	* 	If $_GET['__api'] is set, we kill WP and serve up pug bomb awesomeness
	*	@return die if API request
	*/
	public function sniff_requests(){
		global $wp;

		if( isset($wp->query_vars['action']) && $wp->query_vars['action'] == "fe_forgot_password" ){
		
			$this->handle_request();
			exit;
		}
	}
	
	/** Handle Requests
	*	This is where we send off for an intense pug bomb package
	*	@return void 
	*/
	protected function handle_request(){
		global $wp;
		$user = $wp->query_vars['user'];
		
		if(!$user)
			$this->send_response('RUC inválido.');
		$result = custom_retrieve_password($user);
		
		if($result)
			$this->send_response('OK', json_decode($user));
		else
			$this->send_response('Error');
	}
	
	/** Response Handler
	*	This sends a JSON response to the browser
	*/
	protected function send_response($msg, $user = ''){
		$response['message'] = $msg;
		if($user)
			$response['user'] = $user;
		header('content-type: application/json; charset=utf-8');
	    echo json_encode($response)."\n";
	    exit;
	}
}
new Forgot_Password_API_Endpoint();